﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace DataAcquisition
{
    class Message
    {
        public const int HeaderSize = 12;

        public static readonly char[] CtrlType = { 'C', 'T', 'R', 'L' };
        public static readonly char[] DataType = { 'D', 'A', 'T', 'A' };

        public char[] Type { get; set; }
        public short Code { get; set; }
        public short Subcode { get; set; }
        public int DataSize { get; set; }
        public byte[] Data { get; set; }

        public byte[] GetServerMessage()
        {
            byte[] message = new byte[HeaderSize];
            Encoding.ASCII.GetBytes(Type).CopyTo(message, 0);
            BitConverter.GetBytes(IPAddress.HostToNetworkOrder(Code)).CopyTo(message, 4);
            BitConverter.GetBytes(IPAddress.HostToNetworkOrder(Subcode)).CopyTo(message, 6);
            BitConverter.GetBytes(IPAddress.HostToNetworkOrder(DataSize)).CopyTo(message, 8);

            return message;
        }

        public static Message FromServerMessage(byte[] data)
        {
            Message message = new Message();
            message.Type = Encoding.ASCII.GetChars(data.Take(4).ToArray());
            message.Code = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data,4));
            message.Subcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 6));
            message.DataSize = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 8));

            return message;
        }

        public bool IsControlMessage
        {
            get
            {
                return CtrlType.SequenceEqual(Type);
            }
        }

        public bool IsDataMessage
        {
            get
            {
                return DataType.SequenceEqual(Type);
            }
        }
    }
}
